﻿using System;
using System.Collections.Generic;

namespace KouDai.Core.Service.Navigation
{
    public abstract class SimpleNavigateService<TView> : INavigateService
    {
        /// <summary>
        /// 所有ViewModel 和 View对应的容器
        /// </summary>
        private readonly Dictionary<Type, TView> _navMap = new Dictionary<Type, TView>();
        
        /// <summary>
        /// 向容器中注册对应关系
        /// </summary>
        /// <param name="viewModel"></param>
        /// <param name="id">页面的唯一标识</param>
        public void Register(Type viewModel, TView id)
        {
            _navMap.Add(viewModel, id);
        }

        #region implements

        public event EventHandler CanGoBackChanged;

        public abstract bool CanGoBack
        {
            get;
        }

        public void GoBack()
        {
            GoBackCore();
            OnCanGoBackChanged(EventArgs.Empty);
        }

        /// <summary>
        /// 根据viewmodel查找view并分别进行导航
        /// </summary>
        /// <typeparam name="TViewModel"></typeparam>
        public void NavigateTo<TViewModel>(object parameter) where TViewModel : NavigateViewModel
        {
            TView view;
            if (!_navMap.TryGetValue(typeof(TViewModel),out view))
            {
                throw new ArgumentException("没有找到ViewModel与View之间的关系");
            }
            NavigateTo(view, parameter);
            OnCanGoBackChanged(EventArgs.Empty);
        }

        #endregion

        #region Method

        protected abstract void NavigateTo(TView view,object parameter);
        protected abstract void GoBackCore();

        protected virtual void OnCanGoBackChanged(EventArgs e)
        {
            var handler = CanGoBackChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        #endregion
    }
}
